/**
 * Created by Administrator on 2018/12/23.
 */
/* easyui 技术点
*   设置某个tab为选中状态
*   $('#tabs').tabs('select',which); which既可以是title，也可以是index
*
* 获取当前选中的tab，选中的index从0开始
* var tab = $('#tab').tabs('getSelected');
* var index = $('#tab').tabs('getTabIndex',tab);
* */
/*
 * 公共函数库
 */

//1、获取浏览器用于 HTTP 请求的用户代理头的值
var getUserAgent = function(){
    var ua = navigator.userAgent.toLowerCase();
    return ua;
}

//2、判断a是否包含b
var contains = function(a, b) {
    if (a.indexOf(b) != -1) {
        return true;
    }
}

//3、在PC端执行函数
var runOnPC = function(callback){
    if(typeof(callback)==='function'){
        if (!((contains(ua, "android") && contains(ua, "mobile"))
            || (contains(ua, "android") && contains(ua, "mozilla"))
            || (contains(ua, "android") && contains(ua, "opera"))
            || contains(ua, "ucweb7") || contains(ua, "iphone")
            || contains(ua, "micromessenger")/*微信默认浏览器*/)) {
            callback();
        }
    }
}

//4、在手机端执行函数
var runOnMobile = function(callback){
    if(typeof(callback)==='function'){
        if ((contains(ua, "android") && contains(ua, "mobile"))
            || (contains(ua, "android") && contains(ua, "mozilla"))
            || (contains(ua, "android") && contains(ua, "opera"))
            || contains(ua, "ucweb7") || contains(ua, "iphone")
            || contains(ua, "micromessenger")/*微信默认浏览器*/) {
            callback();
        }
    }
}

//5、获取cookie值
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);//去掉空字符
        //目前大多数浏览器所使用的cookie，对于特殊字符如@，是不兼容的，会自动加上双引号
        while (c.indexOf('\"')!=-1) c = c.replace('\"','');
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

/**
 * 弹出顶置新窗口
 * @param popurl		新窗口的地址
 * @param popTitle		新窗口标题
 * @param popWidth		新窗口宽度
 * @param popHeight		新窗口高度
 * @param options		用于传递给下个窗口的变量或者函数（新窗口用parentWinowOption.变量名或者方法名  可调用父窗口的变量或方法）
 * @returns
 */
function openTopWindow(popurl,popTitle,popWidth,popHeight,options) {
    var url = popurl;//POP框URL
    var popW =  popWidth;//POP框宽度
    var popH =  popHeight;//POP框高度
    var popT =  popTitle;//POP框标题
    if (!options) {
        options = new Object();
    }
    var popDialog = top.$('<div />').dialog({
        closable: true,
        collapsible: true,
        title : popT,
        content : '<iframe id="" src="' + url + '" allowTransparency="true"  scrolling="auto" width="100%" height="98%" frameBorder="0" name=""></iframe>',
        width : popW,
        height : popH,
        modal : true,
        maximizable : true,
        resizable : true,
        toolbar:[{
            text:'',
            iconCls:'icon-cancel',
            handler:function(){
                popDialog.dialog('close');
                options.reloadGrid();
            }
        }],
        /*buttons: [{
            text: '关闭',
            iconCls: 'icon-cancel',
            left: 55,
            handler: function () {
                popDialog.dialog('close');
            }
        }],*/
        onClose : function() {
            popDialog.dialog('destroy').remove();
        }
    });
    // 定义关闭窗口方法供下个窗口关闭
    options.closeIframeWindow = function(){
        popDialog.dialog('close',true);
    }
    // 给新窗口定义变量传递参数或方法
    popDialog.find('iframe').get(0).contentWindow.parentWinowOption = options;
}

/*
 * 异步AJAX，post数据
 */
function postAsyncAjax(url, data) {
    var json = null;
    $.ajax({
        type : "POST",
        url : url,
        data : data,
        async : true,
        dataType : "json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success : function(msg) {
            if(msg.toString().indexOf("window")>0)window.top.location.href='/index';
            json = msg;
            return json;
        },
        error : function(request) {
            alert("加载超时！");
        }
    });
    return json;
}

/*
 * 同步AJAX，post数据
 */
function postSyncAjax(url, data) {
    var json = null;
    $.ajax({
        type : "POST",
        url : url,
        data : data,
        async : false,
        dataType : "json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        success : function(msg) {
            if(msg.toString().indexOf("alert")>0 ){
                $.messager.alert('提示',msg,'info',function(){
                    if(msg.toString().indexOf("超时")>0){
                        window.top.location.href='/index';
                    }
                });
            }

            if(msg.toString().indexOf("window")>0)window.top.location.href='/index';
            json = msg;
        },error : function(request) {
            json = request;
        }
    });
    return json;
}

/*
 * 同步AJAX，post数据
 * 在 JQuery ajax() 方法中设置contentType = false,不冲突。
 * 因为当查看这时的 Request headers，会发现还是有分界符。
 * 因为当我们在 form 标签中设置了enctype = “multipart/form-data”,
 * 这样请求中的 contentType 就会默认为 multipart/form-data 。
 * 而在 ajax 中 contentType 设置为 false 是为了避免 JQuery
 * 对其操作，从而失去分界符，而使服务器不能正常解析文件
 * 需要借助ajaxfileupload.js的ajaxFileUpload方法
 */
function postIncludeFileSyncAjax(url, data) {
    var json = null;
    $.ajax({
        type : "POST",
        url : url,
        data : data,
        async : true,
        cache: false,
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false,//必须
        beforeSend:function(){
            console.log("正在进行，请稍候");
        },
        success : function(msg) {
            if(msg.toString().indexOf("alert")>0 ){
                $.messager.alert('提示',msg,'info',function(){
                    if(msg.toString().indexOf("超时")>0){
                        window.top.location.href='/index';
                    }
                });
            }

            if(msg.toString().indexOf("window")>0)window.top.location.href='/index';
            json = msg;
        },error : function(request) {
            console.log(request);
            json = request;
        }
    });
    return json;
}

function showDialogWithContent(content) {
    console.log(top);
    var newH = "<div id=\"dlg\" class=\"easyui-dialog\" title=\"提示框\""+
            " data-options=\"iconCls:'icon-save'\""+
            " style=\"width:250px;height:130px;padding:10px\">"+
            content+"</div>";
    var obj = $("#dlg");
    if(obj.length <= 0){
        var targetObj = top.$('<div />').append(newH);
        $.parser.parse(targetObj);// 重新渲染某个特定的组件，解决样式丢失的问题
        obj.dialog("open");
        showDialogWithContent(content);
    } else{
        obj.html(content).dialog("open");
        setTimeout(function () {
            obj.dialog("close");
        },2000);
    }
}

function showDialogWithFunc(content,func) {
    var newH = "<div id=\"dlg1\" class=\"easyui-dialog\" title=\"提示框\""+
        " data-options=\"iconCls:'icon-save'\""+
        " style=\"width:250px;height:130px;padding:10px\">"+
        content+"</div>";
    var obj = $("#dlg1");
    if(obj.length <= 0){
        var targetObj = top.$('<div />').append(newH);
        $.parser.parse(targetObj);// 重新渲染某个特定的组件，解决样式丢失的问题
        obj.dialog("open");
        showDialogWithFunc(content,func);
    }else {
        obj.html(content).dialog("open");
        setTimeout(function () {
            obj.dialog("close");
            func();
        },2000);
    }
}

function showDialogSetTime(content,func,invokeTime) {
    var invokeT = 1000;//function调用定时时间
    if(null!=invokeTime) invokeT = invokeTime;
    var newH = "<div id=\"dlg2\" class=\"easyui-dialog\" title=\"提示框\""+
        " data-options=\"iconCls:'icon-save'\""+
        " style=\"width:250px;height:130px;padding:10px\">"+
        content+"</div>";
    var obj = $("#dlg2");
    if(obj.length <= 0){
        var targetObj = top.$('<div />').append(newH);
        $.parser.parse(targetObj);// 重新渲染某个特定的组件，解决样式丢失的问题
        obj.dialog("open");
        showDialogSetTime(content,func,invokeTime);
    } else {
        obj.html(content).dialog("open");
        setTimeout(function () {
            obj.dialog("close");
            func();
        },invokeT);
    }
}

function showDialogWithBtn(content,func) {
    var newH = "<div id=\"dlg3\" class=\"easyui-dialog\" title=\"提示框\""+
        " data-options=\"iconCls:'icon-tip'\""+
        " style=\"width:250px;height:130px;text-align:center;line-height:40px;\">"+
        content+"<br/><a id=\"okBtn3\" href=\"javascript:void(0)\""+
        " class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-ok'\">确定</a></div>";
    var obj = $("#dlg3");
    if(obj.length <= 0){
        var targetObj = top.$('<div />').append(newH);
        $.parser.parse(targetObj);// 重新渲染某个特定的组件，解决样式丢失的问题
        obj.dialog("open");
    } else {
        var btn = "<br/><a id=\"okBtn3\" href=\"javascript:void(0)\""+
            " class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-ok'\">确定</a>";
        obj.html(content).dialog("open");
        var btnObj = obj.append(btn);
        $.parser.parse(btnObj);
    }
    $("#okBtn3").click(function () {
        func();
        obj.dialog("close");
    });
}

function closeDialog(obj) {
    obj.dialog("close");
}

function selectPanel(id,paneltitle){
    if (paneltitle){
        $('#'+id).accordion('select',paneltitle);
    }
}

function addPanel(id,title,icon,content){
    $('#'+id).accordion('add',{
        title:title,
        iconCls:icon,
        content:content,
        selected: true,
        heightStyle:"auto"
    });
}

function removePanel(id){
    var pp = $('#'+id).accordion('getSelected');
    if (pp){
        var index = $('#'+id).accordion('getPanelIndex',pp);
        $('#'+id).accordion('remove',index);
    }
}

function goToPanel(id) {
    
}

function addAccordion(id,title,icon,content,sum){
    if(sum==1){
        $('#'+id).accordion('add', {
            title: title,
            iconCls:icon,
            content: content,
            selected: true
        });
    }else{
        $('#'+id).accordion('add', {
            title: title,
            iconCls:icon,
            content: content,
            selected: false
        });
    }
}

function addTabs(params){
    var tabsZone = top.$("#"+params.id);
    var url = params.url;
    var title = params.title;
    var cssid = params.cssid;
    var flag = tabsZone.tabs('exists',title);
    var iframe = '<iframe src="' + url + '" frameborder="0" id="'
        + cssid
        + '" style="border:0;width:100%;height:100%;"></iframe>';
    if(!flag){
        tabsZone.tabs('add',{
            title: title,
            content: iframe,
            fit : true,
            closable: true,
            tools : [{
                iconCls : 'icon-mini-refresh',
                handler : function() {
                    RefreshTab(params.id);
                }
            } ]
        });
    }
}

function RefreshTab(id) {
    var currentTab = top.$('#'+id).tabs('getSelected');
    var url = $(currentTab.panel('options')).attr('href');
    top.$('#'+id).tabs('update', {
        tab: currentTab,
        options: {
            href: url
        }
    });
    currentTab.panel('refresh');
}

var createTabs = function(id, url, title,cssid) {
    var obj = new Object();
    obj.id = id;//内容区域id
    obj.url = url;
    obj.title = title;
    obj.cssid = cssid;
    var flag = top.$("#"+id).tabs('exists',title);
    if(flag){
        top.$("#"+id).tabs("select",title);//切换选中tabs
    } else {
        addTabs(obj);
    }
    changeLeftCss(cssid);
}
//关闭标签页
var removeTabs = function(id, title){
    var flag = top.$("#"+id).tabs('exists',title);
    if(flag){
        top.$("#"+id).tabs("close",title);
    }
}

changeLeftCss = function(cssid) {
    if ($('.easyui-accordion div[class^="active"]') != null) {
        $('.active').removeClass('active');
        $('.neuactive').removeClass('neuactive');
    }

    $("#" + cssid).parent().addClass('active');
    $("#" + cssid).addClass('neuactive');
}

/**************************************时间格式化处理************************************/
function dateFtt(fmt,date)
{ //author: meizz
    var o = {
        "M+" : date.getMonth()+1,                 //月份
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //小时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
        "q+" : Math.floor((date.getMonth()+3)/3), //季度
        "S"  : date.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}

//修改日历框的显示格式
function formatter(date){
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    hour = hour < 10 ? '0' + hour : hour;
    return year + "-" + month + "-" + day + " " + hour;
}

function parser(s){
    var t = Date.parse(s);
    if (!isNaN(t)){
        return new Date(t);
    } else {
        return new Date(s + ":00:00");
    }
}

/**
 * 页面时间运算
 *
 * @param date
 *            当前日期
 * @param days
 *            1为加一天 -1为减一天
 * @returns {String}
 */
function addDate(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var m = d.getMonth() + 1;
    m = d.getFullYear() + '-' + m + '-';
    if(d.getDate()<10){
        m+="0"+ d.getDate();
    }else{
        m+=d.getDate();
    }
    return m;
}
var contains = function(a, b) {
    if (a.indexOf(b) != -1) {
        return true;
    }
};
function isPhone() {
    var result;
    var ua = navigator.userAgent.toLowerCase();
    //console.log("userAgent:" + ua);
    if (contains(ua, "ipad") || (contains(ua, "rv:1.2.3.4"))
        || (contains(ua, "0.0.0.0")) || (contains(ua, "8.0.552.237"))) {
        result = false
    }
    if ((contains(ua, "android") && contains(ua, "mobile"))
        || (contains(ua, "android") && contains(ua, "mozilla"))
        || (contains(ua, "android") && contains(ua, "opera"))
        || contains(ua, "ucweb7") || contains(ua, "iphone")
        || contains(ua, "micromessenger")/*微信默认浏览器*/) {
        result = true;
    } else {
        result = false;
    }
    //console.log(result);
    return result;
}

// 根据角色id获取对应的权限
var roleLimitTool = {
    // 获取数组
    getRoleLimit : function () {
        if(this.rLimits == null) {
            this.rLimits = new Array();
        }
        return this.rLimits;
    },
    // 查询指定角色的所有权限，存在数组里
    queryRoleLimit : function () {
        var jsonStr = postSyncAjax("/queryLimitByRole/normal", null);
        //console.log("roleLimitTool");
        //console.log(jsonStr);
        var rLimit = this.getRoleLimit();
        if(!jsonStr.success) {
            return;
        }
        var limits = jsonStr.data;
        $.each(limits, function (index, ele) {
            var lim = new Object();
            lim.limitId = ele.limitId;
            lim.limitName = ele.limitName == null || ele.limitName == undefined ? "" : ele.limitName;
            lim.addr = ele.addr == null || ele.addr == undefined ? "" : ele.addr;
            lim.icon = ele.icon == null || ele.icon == undefined ? "" : ele.icon;
            lim.limitType = ele.limitType == null || ele.limitType == undefined ? "" : ele.limitType;
            lim.parentCode = ele.parentCode == null || ele.parentCode == undefined ? "" : ele.parentCode;
            lim.openStyle = ele.openStyle == null || ele.openStyle == undefined ? "" : ele.openStyle;
            lim.limitCode = ele.limitCode == null || ele.limitCode == undefined ? "" : ele.limitCode;
            rLimit.push(lim);
        });
        this.rLimits = rLimit;
    },
    // 是否拥有指定权限
    isLimitBeyondToRole : function (limitId) {
        var rLimit = this.getRoleLimit();
        for(var j = 0; j < rLimit.length; j++) {
            var limit = rLimit[i];
            if(null != limit && null != limit.limitId &&
                limit.limitId == limitId) {
                return true;
            }
        }
        return false;
    },
    // 获取权限名称
    getLimitNameById : function (limitId) {
        var rLimit = this.getRoleLimit();
        for(var j = 0; j < rLimit.length; j++) {
            var limit = rLimit[i];
            if(null != limit && null != limit.limitId &&
                limit.limitId == limitId) {
                return limit.limitName;
            }
        }
        return '';
    },
    // 获取指定父级权限的子权限
    getLimitObjectByParentCode : function (parentCode) {
        var rLimit = this.getRoleLimit();
        var theLimits = new Array();
        var flag = false;
        for(var j = 0; j < rLimit.length; j++) {
            var limit = rLimit[j];
            if(null != limit && null != limit.parentCode &&
                limit.parentCode == parentCode) {
                for(var k =0; k < theLimits.length; k++) {
                    if(theLimits[k].limitId == limit.limitId) {
                        flag = true;
                        continue;
                    }
                }
                if(!flag) {
                    theLimits.push(limit);
                } else {
                    flag = false;
                }
            }
        }
        return theLimits;
    },
    // 权限是否归属于指定父级权限集合
    isLimitBeyondToParentCodes : function (parentCodes, limitId) {
        if(null == parentCodes || parentCodes.length <= 0) return false;
        for(var i =0; i < parentCodes.length; i++) {
            var parentCode = parentCodes[i];
            if(null == parentCode || undefined == parentCode) continue;

            var theLimits = this.getLimitObjectByParentCode(parentCode);
            for(var j = 0; j < theLimits.length; j++) {
                var limit = theLimits[j];
                if(null != limit && null != limit.limitId &&
                    limit.limitId == limitId) {
                    return true;
                }
            }
        }
        return false;
    },
    //权限是否归属于指定父级权限
    isLimitBeyondToTheParentCode : function (parentCode, limitId) {
        if(null == parentCode || undefined == parentCode) return false;
        var theLimits = this.getLimitObjectByParentCode(parentCode);

        for(var j = 0; j < theLimits.length; j++) {
            var limit = theLimits[j];
            if(null != limit && null != limit.limitId &&
                limit.limitId == limitId) {
                return true;
            }
        }
        return false;
    }
}

// 查询角色菜单信息
var queryMenuLimitByRoleId = function (roleId) {
    var params = new Object();
    params.roleId = roleId;
    var jsonStr = postSyncAjax("/queryMenuLimitByRoleId/normal", params);
    return jsonStr.data;
}
// 查询工具栏按钮信息
var queryButtonLimit = function(parentCode) {
    // 按钮(添加，修改，删除)
    var params = new Object();
    params.parentCode = parentCode;
    var jsonStr = postSyncAjax("/queryButtonLimitByParentCode/normal", params);
    console.log(jsonStr);
    if (jsonStr.data == null) jsonStr.data = [];
    var arr = jsonStr.data;
    //if(arr==undefined){window.top.location.reload();}
    var param = []; //toolbar
    var addrArray = [];
    $.each(arr, function (index,ele) {
        //addrArray[ele.limitName] = ele.addr;
        param.push({
            code : ele.limitCode,
            text : ele.limitName,
            iconCls : ele.icon,
            handler : function() {
                eval('('+ele.addr+')');
            }
        });
        param.push('-');
    });
    return param;
}

// 打开信息栏
var openMessageZone = function (src) {
    top.$("#main-zone").find("#regionEast").panel({width:600}); // easyui-layout 调整布局大小
    top.$("#main-zone").layout('resize');// easyui-layout 调整布局大小
    top.$("#main-zone").find("iframe").eq(0).attr("src",src);
    top.$("#main-zone").layout("expand","east");
    /*var p = top.$("#main-zone").layout("panel", "east")[0].clientWidth;
    if (p > 0)
        top.$("#main-zone").layout("collapse", "east");
    else
        top.$("#main-zone").layout("expand","east");*/
}

// 编辑表单提交
var editFormSubmit = function (editForm, url) {
    if(editForm.form("enableValidation")) {
        editForm.form('submit', {
            url: url,
            success:function (result) {
                var r = $.parseJSON(result);
                if(r.success) {
                    $.messager.alert("消息提示","编辑成功！","info");
                } else {
                    if (result.status == 401) {
                        $.messager.alert("消息提示",r.msg,"warning",
                            function () {
                                window.top.location.href = "/index";
                            });
                    }
                    $.messager.alert("消息提示","编辑失败：" + r.msg,"warning");
                    return;
                }
            }
        });
    }
}
// 保存表单提交
var saveFormSubmit = function (saveForm, url) {
    if(saveForm.form("enableValidation")) {
        saveForm.form('submit', {
            url: url,
            success:function (result) {
                var r = $.parseJSON(result);
                if(r.success) {
                    $.messager.alert("消息提示","保存成功！","info");
                } else {
                    if (result.status == 401) {
                        $.messager.alert("消息提示",r.msg,"warning",
                            function () {
                                window.top.location.href = "/index";
                            });
                    }
                    $.messager.alert("消息提示","保存失败：" + r.msg,"warning");
                    return;
                }
            }
        });
    }
}

// 获取地址栏参数
var locations = {
    ParamString : function(val) {
        var uri = window.location.search;
        var re = new RegExp("" + val + "\=([^\&\?]*)", "ig");
        return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1))
            : null);
    }
}

// 创建菜单对应的标签栏
var createMenuTabs = function(id, url, title,cssid) {
    var obj = new Object();
    obj.id = id;//内容区域id
    obj.url = url;
    obj.title = title;
    obj.cssid = cssid;
    var flag = top.$("#"+id).tabs('exists',title);
    if(flag){
        top.$("#"+id).tabs("select",title);//切换选中tabs
    } else {
        addMenuTabs(obj);
    }
    changeLeftCss(cssid);
}

// 添加菜单对应的标签栏，并传递parentCode
var addMenuTabs = function(params){
    var tabsZone = top.$("#"+params.id);
    var url = params.url;
    var title = params.title;
    var cssid = params.cssid;
    var parentCode = cssid.replace("menu_","");
    var flag = tabsZone.tabs('exists',title);
    // 多次跳转会丢失parentCode
    var iframe = '<iframe src="' + url + '?parentCode='
        + parentCode + '" frameborder="0" id="'
        + cssid
        + '" style="border:0;width:100%;height:100%;"></iframe>';
    if(!flag){
        tabsZone.tabs('add',{
            title: title,
            content: iframe,
            fit : true,
            closable: true,
            tools : [{
                iconCls : 'icon-mini-refresh',
                handler : function() {
                    RefreshTab(params.id);
                }
            } ]
        });
    }
}

var showThePage = function (parentCode, uri, options) {
    roleLimitTool.queryRoleLimit();
    var theLimits = roleLimitTool.getLimitObjectByParentCode(parentCode);
    var url;
    if(undefined != options && undefined != options.url){
        url = options.url;
    } else {
        url = uri;
    }
    for(var i=0;i < theLimits.length;i++) {
        var l = theLimits[i];
        if(null != l.addr && l.addr.indexOf(uri) != -1) {
            if("messageZone" == l.openStyle) {
                openMessageZone(url);
            } else if("topWindow" == l.openStyle) {
                openTopWindow(url, l.limitName, 600, 600, options);
            } else if("tabs" == l.openStyle) {
                createTabs('sh-tabs', uri, l.limitName,'tabs_' + l.limitCode);
            } else {
                openMessageZone(url);
            }
        }
    }
}

String.prototype.endWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substring(this.length-str.length)==str)
        return true;
    else
        return false;
    return true;
}

String.prototype.startWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substr(0,str.length)==str)
        return true;
    else
        return false;
    return true;
}

